package com.example.shop

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import androidx.databinding.DataBindingUtil
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.example.base.entity.ProductEntityItem
import com.example.shop.databinding.ItemProductBinding

class ProductPageAdapter :PagingDataAdapter<ProductEntityItem,ProductPageAdapter.ProductViewHolder>(diff){
    private var mOnItemClickListener:OnItemClickListener? = null
    private var mOnItemLongClickListener:OnItemLongClickListener? = null
    companion object{
        val diff = object :DiffUtil.ItemCallback<ProductEntityItem>(){
            override fun areItemsTheSame(
                oldItem: ProductEntityItem,
                newItem: ProductEntityItem
            ): Boolean {
                return oldItem.id==newItem.id
            }

            override fun areContentsTheSame(
                oldItem: ProductEntityItem,
                newItem: ProductEntityItem
            ): Boolean {
                return oldItem==newItem
            }
        }
    }
    class ProductViewHolder(itemView:View):ViewHolder(itemView){
        val binding = DataBindingUtil.bind<ItemProductBinding>(itemView)
    }

    override fun onBindViewHolder(holder: ProductViewHolder, position: Int) {
        holder.binding?.info = getItem(position)
        //进行点击
        holder.itemView.setOnClickListener {
            mOnItemClickListener?.onItemClick(position,getItem(position)!!)
        }
        holder.itemView.setOnLongClickListener {
            mOnItemLongClickListener?.onItemLongClick(position,getItem(position)!!)!!
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder {
        val inflate = LayoutInflater.from(parent.context).inflate(R.layout.item_product, null)
        return ProductViewHolder(inflate)
    }

    fun setOnItemClickListener(listener: OnItemClickListener){
        this.mOnItemClickListener = listener
    }
    fun setOnItemLongClickListener(listener: OnItemLongClickListener){
        this.mOnItemLongClickListener = listener
    }


}

/**
 * 定义接口
 */
interface OnItemClickListener {
    /**
     * Callback method to be invoked when an item in this RecyclerView has
     * been clicked.
     *
     * @param adapter  the adapter
     * @param view     The itemView within the RecyclerView that was clicked (this
     * will be a view provided by the adapter)
     * @param position The position of the view in the adapter.
     */
    fun onItemClick(position: Int,item:ProductEntityItem)
}
//定义长按接口
interface OnItemLongClickListener{

    fun onItemLongClick(position: Int,item: ProductEntityItem):Boolean
}
